import React, { useState, useEffect, useRef } from 'react';
import { View, Text, StyleSheet, ScrollView, Dimensions } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { VictoryPie, VictoryChart, VictoryLine, VictoryAxis, VictoryLabel } from 'victory-native';
import I18n from "react-native-i18n";
const { width } = Dimensions.get('window');
const MoodHistoryPage = () => {
    const [moodHistory, setMoodHistory] = useState([]);
    const scrollViewRef = useRef(null);
    useEffect(() => {
        loadMoodHistory();
    }, []);

    const loadMoodHistory = async () => {
        try {
            const history = await AsyncStorage.getItem('moodHistory');
            if (history) {
                setMoodHistory(JSON.parse(history));
            }
        } catch (error) {
            console.error('Error loading mood history:', error);
        }
    };

    const getMoodCounts = () => {
        const counts = {};
        moodHistory.forEach(entry => {
            if (entry && entry.mood && entry.mood.emoji) {
                const { emoji } = entry.mood;
                counts[emoji] = (counts[emoji] || 0) + 1;
            }
        });
        return Object.entries(counts).map(([emoji, count]) => ({
            x: emoji,
            y: count,
            label: `${emoji}\n${count}`
        }));
    };

    const getMoodTrend = () => {
        return moodHistory.map((entry, index) => ({
            x: index + 1, // 使用整数作为天数
            y: Math.round(moodToValue(entry.mood.emoji) * 10) / 10
        }));
    };

    const moodToValue = (emoji) => {
        const moodValues = { '😊': 5, '😢': 2, '😠': 1, '😍': 5, '😎': 4, '🤔': 3, '😴': 2, '🙃': 3 };
        return moodValues[emoji] || 3;
    };

    return (
        <ScrollView style={styles.container}
                    ref={scrollViewRef}
                    onContentSizeChange={() => scrollViewRef.current.scrollTo({x: 0, y: 0, animated: true})}
        >
            <Text style={styles.title}>{I18n.t('mood_history')}</Text>

            <View style={styles.chartContainer}>
                <Text style={styles.chartTitle}>{I18n.t('mood_distribution')}</Text>
                <VictoryPie
                    data={getMoodCounts()}
                    colorScale="qualitative"
                    labelRadius={({ radius }) => radius - 30}
                    radius={({ datum }) => 70 + datum.y * 10}
                    innerRadius={50}
                    labels={({ datum }) => `${datum.x}\n${datum.y}`}
                    labelComponent={
                        <VictoryLabel
                            style={{ fill: "black", fontSize: 16, fontWeight: "bold" }}
                            textAnchor="middle"
                        />
                    }
                />
            </View>

            <View style={styles.chartContainer}>
                <Text style={styles.chartTitle}>{I18n.t('mood_trend')}</Text>
                <VictoryChart
                    width={width - 40}  // 减去左右padding
                    height={300}
                    padding={{ top: 20, bottom: 50, left: 50, right: 20 }}
                >
                    <VictoryLine
                        data={getMoodTrend()}
                        style={{
                            data: { stroke: "#c43a31" },
                        }}
                    />
                    <VictoryAxis
                        label={I18n.t('number_of_days')}
                        style={{
                            axisLabel: { padding: 30 },
                            tickLabels: { fontSize: 10, padding: 5 }
                        }}
                        tickFormat={(t) => Math.round(t)}
                    />
                    <VictoryAxis
                        dependentAxis
                        label={I18n.t('mood_value')}
                        domain={[0, 6]}
                        tickValues={[1, 2, 3, 4, 5]}
                        style={{
                            axisLabel: { padding: 30 },
                            tickLabels: { fontSize: 10, padding: 5 }
                        }}
                    />
                </VictoryChart>
            </View>

            <View style={styles.historyList}>
                <Text style={styles.chartTitle}>{I18n.t('detailed_records')}</Text>
                {moodHistory.map((entry, index) => (
                    <View key={index} style={styles.historyItem}>
                        <Text>{new Date(entry.date).toLocaleDateString()}</Text>
                        <Text>{entry.mood.emoji} {entry.mood.label}</Text>
                        <Text>{entry.description}</Text>
                    </View>
                ))}
            </View>
        </ScrollView>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        padding: 10,
        backgroundColor: '#f5f5f5',
    },
    title: {
        fontSize: 24,
        fontWeight: 'bold',
        marginBottom: 20,
    },
    chartContainer: {
        marginBottom: 20,
        backgroundColor: 'white',
        padding: 10,
        borderRadius: 10,
        alignItems: 'center',  // 居中对齐
    },
    chartTitle: {
        fontSize: 18,
        fontWeight: 'bold',
        marginBottom: 10,
    },
    historyList: {
        backgroundColor: 'white',
        padding: 10,
        borderRadius: 10,
    },
    historyItem: {
        marginBottom: 10,
        borderBottomWidth: 1,
        borderBottomColor: '#e0e0e0',
        paddingBottom: 10,
    },
});

export default MoodHistoryPage;
